import serverUrl from '../config/url'
import Vue from 'vue'
import Axios from 'axios'

let utils = {}

utils.fileSaveAs = (url, params) => {
  let paramsStr = ''
  for (let key in params) {
    if (typeof params[key] === 'object') {
      // 对象类型，需要判断是否有id，并拼接成对应的参数格式
      if (params[key].id) {
        paramsStr = paramsStr + `&${key}.id=${params[key].id}`
      }
    } else {
      paramsStr = paramsStr + `&${key}=${params[key]}`
    }
  }

  if (paramsStr.length > 0) {
    paramsStr = `?${paramsStr.substring(1)}`
  }

  let a = document.createElement('a')
  a.href = `${serverUrl}${url}${paramsStr}`
  a.target = '_blank'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

/** 导出需token认证 */
utils.fileExportAs = (url, params, fileName) => {
  let paramsStr = ''
  for (let key in params) {
    if (typeof params[key] === 'object') {
      // 对象类型，需要判断是否有id，并拼接成对应的参数格式
      if (params[key].id) {
        paramsStr = paramsStr + `&${key}.id=${params[key].id}`
      }
    } else {
      paramsStr = paramsStr + `&${key}=${params[key]}`
    }
  }
  if (paramsStr.length > 0) {
    paramsStr = `?${paramsStr.substring(1)}`
  }
  Axios
    .get(`${url}${paramsStr}`, {
      responseType: 'blob'
    })
    .then(resp => {
      let blob = new Blob([resp], {
        type: 'application/octet-stream'
      })
      let a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.target = '_blank'
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
}

utils.treeToArray = (treeData, parent, level, expandedAll) => {
  let tempArr = []

  treeData.forEach((element) => {
    if (typeof (element._expanded) === 'undefined') {
      Vue.set(element, '_expanded', expandedAll)
    }

    if (parent) {
      Vue.set(element, '_parent', parent)
    }

    let _level = 0
    if (level !== null && level !== undefined) {
      _level = level + 1
    }

    Vue.set(element, '_level', _level)

    tempArr.push(element)

    if (element.children && element.children.length > 0) {
      let children = utils.treeToArray(element.children, element, _level, expandedAll)
      tempArr = tempArr.concat(children)
    }
  })

  return tempArr
}

export default utils
